import React, {useEffect, useState} from "react";
// @ts-ignore
import styled from "styled-components";
import Container from "./Container";

interface ItemType {
  id: number;
  name: string;
  children?: Array<ItemType>
}

const ItemBox = styled.div`
  border: 1px solid black;
  min-height: 50px;
  min-width: 100px;
  width: 100%;
  padding: 10px 20px;
  box-sizing: border-box;
  margin: 10px 0 10px 10px;
`;

function setList() {
  return function () {

  };
}

interface INestedContainers {
  index: number;
  item: any;
  children?: any;
  onChange?: (a: Array<any>, index?: number) => void
  setStateCopy: any
}

// @ts-ignore
function flatten(items: any[], parentId = null, depth = 0) {
  return items?.reduce((acc, item, index) => {

    let children = [];
    if (Array.isArray(item.children)) {
      children = flatten(item.children, item.soleId, depth + 1);
    }
    return [
      ...acc,
      {...item, parentId, depth, index},
      ...children,
    ];
  }, []);
}

function findItem(items: any[], itemId: any) {
  return items.find(({soleId}) => soleId === itemId);
}

function buildTree(flattenedItems: any) {
  const root = {soleId: 'root', children: []};
  const nodes = {[root.soleId]: root};

  for (const item of flattenedItems) {
    const {soleId, children} = item;
    const parentId = item.parentId ?? root.soleId;
    const parent = nodes[parentId] ?? findItem(flattenedItems, parentId);

    nodes[soleId] = {soleId, children};
    if (Array.isArray(parent.children)) {
      // @ts-ignore
      const a = parent.children.find(k => k.soleId === item.soleId);
      if (parent.children.length === 0 || !a) {
        // @ts-ignore
        parent.children.push(item);
      }
    }
  }

  return root.children;
}

let flatteningState: never[] = [];

function addSoleId(list: Array<{ soleId: number }>): Array<any> {
  return list.map((k) => {
    if (!k?.soleId) k.soleId = new Date().getTime();
    return k;
  });
}

function NestedContainers(props: INestedContainers) {
  const {item, onChange, index, setStateCopy} = props;

  function copySetState(a: any) {
    a.forEach((k: { soleId: number; }) => {
      if (!k?.soleId) {
        k.soleId = new Date().getTime();

      }
    });
    console.log(22222222, a);
    // @ts-ignore
    const b = flatteningState.findIndex(k => k.soleId === item.soleId);
    if (flatteningState[b]) {
      // @ts-ignore
      flatteningState[b].children = JSON.parse(JSON.stringify(a));
      console.log(111111111111, JSON.parse(JSON.stringify(flatteningState)));
      flatteningState = flatteningState.reduce((acc, item,) => {
        // @ts-ignore
        if (!item?.parentId) {
          acc.push(item);
        }
        return acc;
      }, []);
      setStateCopy(buildTree(flatteningState));
    }

  }

  const [state, setState] = useState(item.children);

  function a(b: any, index: any) {
    console.log(item.name, b);
    const c = JSON.parse(JSON.stringify(item));
    c.children.splice(index, 1, b);
    onChange?.(c);
  }

  function onChanges(evt: any) {
    console.log(evt, 11111111111);
  }

  function onAdd(evt: any) {
    const {oldIndex, newIndex} = evt;
    setState((item: any) => {
      const interiorItem = JSON.parse(JSON.stringify(item));

      interiorItem.splice(newIndex, 0,);
      return interiorItem;
    });
  }

  return (
    <ItemBox>
      {item.name}{item.soleId}
      {
        Array.isArray(item.children)
        &&
        <Container
          list={item.children}
          setList={copySetState}
          containerId={item.id}
          isPut={(activeId: string, overId: string) => {
            return true;
          }}
          style={{
            border: '1px solid red',
            width: '100%',
            minHeight: 300,
            padding: '10px 20px',
            margin: 'auto',
            boxSizing: 'border-box'
          }}
        >
          {
            item.children.map((k: { name: any; }, i: number) => {
              return <NestedContainers key={i} item={k} index={i} setStateCopy={setStateCopy}/>;
            })
          }
        </Container>
      }
    </ItemBox>
  );
}

export default function () {
  const [state] = useState<Array<ItemType>>([
    {id: 2, name: "shrek", children: []},
    {
      id: 4,
      name: "aaaaa",
      children: []
    },
    {id: 3, name: "fiona"},
  ]);
  const [stateCopy, setStateCopy] = useState<Array<ItemType>>([]);
  flatteningState = JSON.parse(JSON.stringify(flatten(stateCopy)));


  function copySetStateCopy(a: any) {
    setStateCopy(addSoleId(a));
  }

  useEffect(() => {
    console.log('同步获取:', stateCopy);
  }, [stateCopy]);

  return (
    <>
      <Container
        list={state}
        setList={() => {
        }}
        noSort
        style={{
          display: "flex",
          justifyContent: 'center',
          padding: '10px'
        }}
      >
        {
          state.map((item, i) => {
              return <ItemBox key={item.id}>
                {item.name}
              </ItemBox>;
            }
          )
        }
      </Container>

      <Container
        list={stateCopy}
        setList={copySetStateCopy}
        style={{
          border: '1px solid red',
          width: 800,
          minHeight: 300,
          padding: '10px 20px',
          margin: 'auto'
        }}
      >
        {
          stateCopy.map((item, i) => {
              return <NestedContainers key={i} item={item} index={i} setStateCopy={setStateCopy}/>;
            }
          )
        }
      </Container>
    </>
  );
}

